package com.huifaapp.mall.selectImage;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;


import com.huifaapp.mall.R;
import com.huifaapp.mall.uitils.ToastUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by chen on 2017/6/21.
 */

public class SelectImageView extends BaseFragment {
    GridView gridImages;
    public static final String TAG = "SelectImageView";
    int maxNum = 9; //最多选择图片数量
    int numColumns = 3; //列数
    List<ImagePath> pathList;
    ImagePath addImagePath = new ImagePath();

    ImageAdapter adapter;

    ScreenMenu deleteMenu;
    SelectPicMenu picMenu;
    int deletePosition;

    public void setMaxNum(int maxNum) {
        this.maxNum = maxNum;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_select_image;
    }

    @Override
    protected void initialize() {
        pathList = new ArrayList<>();
        addImagePath.setId(-1);

        adapter = new ImageAdapter(baseActivity, pathList);

        deleteMenu = new ScreenMenu(baseActivity);
        deleteMenu.setAdapter(new SelectAdapter(baseActivity, new String[]{"删除"}, true));
        deleteMenu.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    pathList.remove(deletePosition);
                    if (pathList.size() < maxNum && pathList.indexOf(addImagePath) == -1) {
                        pathList.add(addImagePath);
                    }
                    adapter.notifyDataSetChanged();
                }
            }
        }).create();

        picMenu = new SelectPicMenu(baseActivity);
        picMenu.setIsOperate(true);
        picMenu.create();
        picMenu.setOnSelectMenuClickListener(new SelectPicMenu.OnSelectMenuClickListener() {
            @Override
            public int onClick() {
                int selectImageNum = maxNum - pathList.size() + 1;
                if (selectImageNum == 0) {
                    ToastUtil.showL(baseActivity, "亲，最多只能选择" + maxNum + "张图片哦，删除几张再来点我吧");
                }
                return selectImageNum;
            }
        });
    }

    @Override
    protected void initView() {
        gridImages = (GridView) findViewById(R.id.gridImages);
        gridImages.setNumColumns(numColumns);

        if (pathList.size() < maxNum) {
            pathList.add(addImagePath);
        }
        gridImages.setAdapter(adapter);

        gridImages.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                if (adapter.getItem(position).getId() == -1) {
                    picMenu.show();
                } else {
                    ArrayList<String> imageList = new ArrayList<>();
                    for (ImagePath imagePath : pathList) {
                        if (imagePath.getId() != -1) {
                            imageList.add(imagePath.getUrl());
                        }
                    }
                    Intent intent = new Intent(baseActivity, ImageGalleryActivity.class);
                    intent.putStringArrayListExtra(ImageGalleryActivity.EXTRA_IMAGES, imageList);
                    intent.putExtra(ImageGalleryActivity.EXTRA_POSITION, position);
                    baseActivity.startActivity(intent);
                }
            }
        });

        gridImages.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long l) {
                if (adapter.getItem(position).getId() != -1) {
                    deletePosition = position;
                    deleteMenu.show();
                }
                return true;
            }
        });
    }

    private void addImagePath(ImagePath imagePath){
        if (pathList.indexOf(addImagePath) != -1) {
            pathList.add(pathList.indexOf(addImagePath), imagePath);
        } else {
            pathList.add(0, imagePath);
        }
        if (pathList.size() > maxNum) {
            pathList.remove(addImagePath);
        }
    }

    public static boolean isGifFile(File file) {
        try {
            FileInputStream inputStream = new FileInputStream(file);
            int[] flags = new int[5];
            flags[0] = inputStream.read();
            flags[1] = inputStream.read();
            flags[2] = inputStream.read();
            flags[3] = inputStream.read();
            inputStream.skip(inputStream.available() - 1);
            flags[4] = inputStream.read();
            inputStream.close();
            return flags[0] == 71 && flags[1] == 73 && flags[2] == 70 && flags[3] == 56 && flags[4] == 0x3B;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public List<ImagePath> getPathList(){
        return pathList;
    }

    @Override
    public void onActivityResult(int requestCode, int arg1, Intent arg2) {
        super.onActivityResult(requestCode, arg1, arg2);
        if (arg1 == 2 && arg2 != null) {//相册选择的activity返回的结果
            for (String path : arg2.getStringArrayListExtra("paths")) {
                int[] size = BitmapCondense.computOriginalSize(path);
                ImagePath xyImagePath = new ImagePath();
                if (isGifFile(new File(path))) {
                    xyImagePath.setIs_gif(1);
                }
                xyImagePath.setWidth(size[0]);
                xyImagePath.setHeight(size[1]);
                xyImagePath.setUrl(path);
                addImagePath(xyImagePath);
            }
            adapter.notifyDataSetChanged();
        }  else if (SelectPicMenu.FLAG_CHOOSE_PHONE == requestCode && arg1 == -1){//拍照之后跳转到的activity
            Intent intent = new Intent(baseActivity, PhoneConfirmActivity.class);
            intent.putExtra("path", picMenu.getFileImageName());
            baseActivity.startActivityForResult(intent, 10);
            return;
        } else if (arg1 == PhoneConfirmActivity.RESCODE_PATH && arg2 != null) {//拍照之后跳转到的activity返回的结果
            String imgPath = arg2.getStringExtra("path");
            if (TextUtils.isEmpty(imgPath)) {
                return;
            }
            ImagePath xyImagePath = new ImagePath();
            xyImagePath.setUrl(imgPath);
            int[] size = BitmapCondense.computOriginalSize(imgPath);
            xyImagePath.setWidth(size[0]);
            xyImagePath.setHeight(size[1]);
            addImagePath(xyImagePath);
            adapter.notifyDataSetChanged();
        }
    }
}
